#include <stdlib.h>
#include<ctime>
#include"RingQueue.hpp"
#include"Task.hpp"
 #include <unistd.h>

 std::string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

void* ProductorRoutine(void* arg)
{
    RingQueue<Task>* rqt = static_cast<  RingQueue<Task>*> (arg);
    while(true)
    {
        sleep(1);
        int x =rand()%50+1;
        int y =rand()%20+1;
        int op = rand()%oper.size();
        Task t(x,y,oper[op],mymath);
        rqt->push(t);
        std::cout <<  SelfName() << ", 生产者派发了一个任务: " << t.toTaskString() << std::endl;
    }
    return nullptr;
}

void* ConsumerRoutine(void* arg)
{
    RingQueue<Task>* rqt = static_cast<  RingQueue<Task>*> (arg);
    while(true)
    {
        Task t;
        rqt->pop(&t);
        std::string result = t();
         std::cout <<  SelfName() << ", 消费者消费了一个任务: " << result << std::endl;
         sleep(1);
    }
}
int main()
{
     // 生成随机数种子
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self() ^ 0x71727374);
    RingQueue<Task>* rqt = new RingQueue<Task>();

    pthread_t p[4],c[8]; // 4个生产者 8个消费者
    for(int i =0;i<4;i++)
    {
        pthread_create(p+i,nullptr,ProductorRoutine,rqt);
    }

    for(int i =0;i<8;i++)
    {
        pthread_create(c+i,nullptr,ConsumerRoutine,rqt);
    }

    for(int i =0;i<4;i++)
    {
        pthread_join(p[i],nullptr);
    }
    for(int i =0;i<8;i++)
    {
        pthread_join(c[i],nullptr);
    }
    delete rqt;

    return 0;
}